package com.xwj.back.utils.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xwj.back.mapper.StoreMapper;
import com.xwj.back.pojo.Store;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DataListener extends AnalysisEventListener<Store> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataListener.class);
    private static final int BATCH_COUNT = 8;
    private static final String logoUrl = "https://s1.ax1x.com/2023/02/09/pSWOnUI.png";
    List<Store> list = new ArrayList<>();
    private final StoreMapper storeMapper;


    public DataListener(StoreMapper storeMapper) {
        this.storeMapper = storeMapper;
    }


    @Override
    public void invoke(Store store, AnalysisContext analysisContext) {
        store.setId(null);
        if(store.getLogo() == null ||"".equals(store.getLogo())){
            store.setLogo(logoUrl);
        }
        list.add(store);
        if(list.size() >= BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    //存储到数据库
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        for (Store store : list) {
            storeMapper.insert(store);
        }
        LOGGER.info("存储数据库成功！");
    }
}